package com.world.rickcloudendpoint.common;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 线程名字工厂
 * @author: jlsong
 * @date: 2021/12/22 21:15:21
 * @version: 1.0
 */
public class ThreadNameFactory implements ThreadFactory {
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(0);
    private final String namePrefix;
    private final boolean daemon;

    public ThreadNameFactory(String namePrefix) {
        this(namePrefix, false);
    }

    public ThreadNameFactory(String namePrefix, boolean daemon) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.namePrefix = namePrefix + "-thread-";
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix +
                threadNumber.getAndIncrement(), 0);
        if (daemon){
            t.setDaemon(true);
        }else {
            if (t.isDaemon()){
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY){
                t.setPriority(Thread.NORM_PRIORITY);
            }
        }
        return t;
    }

    public String getNamePrefix() {
        return namePrefix;
    }
}
